const Koa = require('koa');
const cors = require('koa-cors');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const fs=require('fs')
const path=require('path')
const UserJSON=path.join(__dirname,'../','Server/','data/','user.json')
const jwt=require('jsonwebtoken')
const Mock=require('mockjs')
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const app = new Koa();
const router = new Router();
// 素材
let material=[
    {
        title:"节日素材",
        children:[
            {
                img:"https://img1.baidu.com/it/u=163589145,440597166&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800"
            },
             {
                img:"https://img2.baidu.com/it/u=2566953024,2722720857&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
            },
             {
                img:"https://img1.baidu.com/it/u=2898934632,2693533509&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500"
            },
        ]
    },
    {
        title:"漂浮元素",
        children:[
            {
                img:"https://img1.baidu.com/it/u=1839145022,1753321155&fm=253&fmt=auto&app=120&f=JPEG?w=531&h=500"
            },
             {
                img:"https://img1.baidu.com/it/u=24540324,1253356227&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1727370000&t=fa76e9182374bab8c69b8fa06fb54f67"
            },
             {
                img:"https://img0.baidu.com/it/u=3081415685,2219539125&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1727370000&t=645e1dc9771cb4fe8760f81d38703324"
            }
        ]
    },
     {
        title:"边框纹理",
        children:[
            {
                img:"https://img1.baidu.com/it/u=4229190809,2298034850&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1727370000&t=387516d8fbdee9fb3e277963acb5570b"
            },
             {
                img:"https://img1.baidu.com/it/u=1653751609,236581088&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
            },
             {
                img:"https://img0.baidu.com/it/u=1654712680,3937550769&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
            }
        ]
    },
      {
        title:"漂浮元素",
        children:[
            {
                img:"https://img1.baidu.com/it/u=1839145022,1753321155&fm=253&fmt=auto&app=120&f=JPEG?w=531&h=500"
            },
             {
                img:"https://img1.baidu.com/it/u=187585967,3882185192&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1727370000&t=feb8c9c15a64a9d658522131d0d38af8"
            },
             {
                img:"https://img0.baidu.com/it/u=1654712680,3937550769&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
            }
        ]
    },
     {
        title:"边框纹理",
        children:[
            {
                img:"https://img0.baidu.com/it/u=3603657669,701688224&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1727370000&t=cac2d0f44ff6032a5d1a474ed0801bdf"
            },
             {
                img:"https://img1.baidu.com/it/u=1653751609,236581088&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
            },
             {
                img:"https://img0.baidu.com/it/u=2233051232,1369302552&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1727370000&t=747a3e2d507a58020cd8513cd0a14660"
            }
        ]
    },
    
]
// 搜索内容
let seach=Mock.mock({
    "seach|50":[
        {
            "name":"@ctitle(5)"
        }
    ]
})

const nav=Mock.mock({
    "title":[
        {
            'name':"图文模版",
            'children|5':[
                {
                    'title':"@ctitle(5)"
                }
            ]
        },
        {
            'name':"片头模版",
            'children|5':[
                {
                    'title':"@ctitle(5)"
                }
            ]
        },
        {
            'name':"背景视频",
            'children|5':[
                {
                    'title':"@ctitle(5)"
                }
            ]
        },
        {
            'name':"字幕花字",
            'children|5':[
                {
                    'title':"@ctitle(5)"
                }
            ]
        },
    ]
})
// 轮播图数据
let Lun=[
    {
        image:"https://js.ibaotu.com/act/24/08/30/66d180e57dcec.jpg",
    },
    {
         image:"https://js.ibaotu.com/act/24/08/30/66d180c9029ae.jpg",
    },
    {       
         image:"https://js.ibaotu.com/act/23/10/16/652cd69cf2edc.jpg",
    },
    {
        image:"https://js.ibaotu.com/act/24/08/05/66b09d5e0ce03.jpg",
    },
    {
         image:"https://js.ibaotu.com/act/24/09/03/66d6a0c103297.jpg"
    }
        
]

// 全部分类数据
const All=Mock.mock({
    "title":[
        {
            'name':"广告设计",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
        {
            'name':"视频音频",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
        {
            'name':"UI新媒体",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
        {
            'name':"办公文档",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
        {
            'name':"电商淘宝",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
        {
            'name':"摄像图",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
         {
            'name':"插画动画",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
         {
            'name':"装饰装修",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
         {
            'name':"3D素材",
            'children|6':[
                {
                    'title':"@ctitle(4)"
                }
            ]
        },
    ]
})


const autoReplies = {
    '你好': '您好，请问需要什么帮助吗!',
    '我想询问一些事情': '好的，请详细说一下!',
    '你可以帮助我吗': '当然可以!',
    '你还好吗': '谢谢我很好',
    '谢谢':'不客气，这是我应该做的!',
    '你今年多大了':'抱歉,这个不在服务范围内',
    '我多大了':'您注册的年龄是20岁',
    '我想寻找我的页面':'您可以去搜索试一试',
    '想要中秋节的海报':'您可以到营销热点里面寻找',
    '我想设计页面':'您可以试着去主页面搜索一下',
};
wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        const receivedMessage = JSON.parse(message);
        setTimeout(() => {
            wss.clients.forEach((client) => {
                if (client.readyState === WebSocket.OPEN) {
                    client.send(message);

                    // 自定义回复
                    const reply = autoReplies[receivedMessage.content.toLowerCase()];
                    if (reply) {
                        const autoReply = {
                            user: '私人客服',
                            content: reply,
                            type: 'text'
                        };
                        client.send(JSON.stringify(autoReply));
                    }
                }
            });
        }, 2000)
    });

    ws.send(JSON.stringify({ user: '私人客服', content: '终于等到您了~很高兴为您服务哟 请您描述下您遇到的问题，您的小可爱正在快马加鞭赶来~', type: 'text' }));
});

console.log('WebSocket server is running on ws://localhost:8080');
// chongzhi
router.get('/api/pay',async (ctx) => {
// 果币 充值
const chongzhi = Mock.mock({
    'list|30': [
        {
            'id|+1': 1,
            'name': '@cname',
            'title': "@ctitle(3,4)",
            'phone': '11122233345',
            'dan':'1287361278312735',
            'yewu|1': ['充值', '订单消费', '退款'],
            'liushui|1': ['收入', '支出'],
           'time':() => Mock.Random.date(),
            "qian|1-2000": 20
        }
    ]
})
    ctx.body = chongzhi
})

// guo 订单
router.get('/api/order',async (ctx) => {
    const order=Mock.mock({
        'list|30':[
            {
                'id|+1': 1,
                'img':'https://ts2.cn.mm.bing.net/th?id=OIP-C.nKetvjjSggVKwC55M-AzUwAAAA&w=250&h=250&c=8&rs=1&qlt=90&r=0&o=6&dpr=1.5&pid=3.1&rm=2',
                'name': '@cname',
                'title': "@ctitle(10,20)",
                'state|1': ['待发货', '已完成', '待付款','已关闭','待收货'],
                'liushui|1': ['收入', '支出'],
                "qian|1-2000": 20,
                'num|1':1,
                "dan":() => Mock.Random.integer(0, 10000000),
                'time':() => Mock.Random.datetime(),

            }
        ]
    })
    ctx.body = order
})

// shop 商品数据
router.get('/api/shop',async(ctx)=>{
    const shop=Mock.mock({
        'list|30':[
            {
                'id|+1': 1,
                'img':'https://ts2.cn.mm.bing.net/th?id=OIP-C.nKetvjjSggVKwC55M-AzUwAAAA&w=250&h=250&c=8&rs=1&qlt=90&r=0&o=6&dpr=1.5&pid=3.1&rm=2',
                'name': '@ctitle(3,7)',
                'title': "@ctitle(10,50)",
                'price|1-900.1-2': 1,
                'num|1-10':1,
                'shou':() => Mock.Random.integer(0, 10000),
                'time':() => Mock.Random.datetime(),
                "state|1":[false,true],
                'hao|1':[true,false],
                "shopda|1":['哈哈','嘻嘻'],
                'shang|1':[true,false],
                "status|1":[true,false],
            }
        ]
    })
    ctx.body = shop
})

router.get('/api/data', async (ctx) => { 
  const mockData = Mock.mock({
    'list|6-12': [
      {
        'id|+1': 1,
        'title':'@csentence',
        'time':'@now',
        'color':'@color'
      },
    ],
  });
  ctx.body = mockData;
});

// 素材
router.get('/material',ctx=>{
    ctx.body={
        code:200,
        msg:"素材数据",
        material
    }
})
// 轮播图数据
router.get('/lun',ctx=>{
    ctx.body={
        code:200,
        msg:"轮播图数据获取成功",
        Lun
    }
})
// 登录
router.post('/login',ctx=>{
    let {username,password}=ctx.request.body
    let userJSONdata=JSON.parse(fs.readFileSync(UserJSON,'utf-8'))
    let user=userJSONdata.find(item=>item.username===username&&item.password===password)
    if(!user){
        return ctx.body= {
            code:401,
            message:'用户名或密码错误'
        }
    }
    return ctx.body={
        code:200,
        message:'登陆成功',
        token:jwt.sign({data: 'foobar'}, 'secret', { expiresIn: 60 * 60 }),
        name:user.name,
        image:user.image,
        userid:user.id
    }
})
// 搜索
router.get('/seach',ctx=>{
    ctx.body={
        code:200,
        msg:"搜索数据",
        seach
    }
})

// 导航栏
router.get('/nav',ctx=>{
    ctx.body={
        code:"导航栏数据",
        msg:'获取成功',
        nav
    }
})

// 全部素材数据

router.get('/all',ctx=>{
    ctx.body={
        code:200,
        msg:"全部素材数据",
        All
    }
})
router.get('/api/color', async (ctx) => {
  const colorData = Mock.mock({
    'list|6-12': [
      {
        'id|+1': 1,
        'title':'@csentence',
        'time':'@now',
        'color':'@color'
      },
    ],
  });
  ctx.body = colorData;
});

app.use(cors());
app.use(bodyParser());
app.use(router.routes());
app.listen(3000, () => {
    console.log('服务器启动成功')
})


